package com.seek.inter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TCustomerAddrbook;
import com.seek.service.CustomerAddrbookService;
import com.seek.service.LoanService;
import com.seek.util.CommonUtil;
import com.seek.util.ConstantsUtil;

/**
 * app中和借款订单相关的服务接口
 *
 */
public class AppLoanInter {
	
	private CustomerAddrbookService customerAddrbookService = (CustomerAddrbookService)SpringContextHolder.getBean("customerAddrbookService");
	private LoanService loanService = (LoanService)SpringContextHolder.getBean("loanService");
	
	/**
	 * 上传紧急联系人
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ResultInfo submitElinkman(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long custId = reqJson.getLong("custId");
		List<JSONObject> data = (List<JSONObject>)reqJson.get("persons");
		if (companyId == null || companyId < 1 || custId == null || custId<1 || data == null || data.size() < 1){
			result.setStatus(1);
			result.setMessage("参数不完整，请检查！"); 
			return result;
		}
		
		List<TCustomerAddrbook> mans = new ArrayList<TCustomerAddrbook>();
		for (JSONObject o : data) {
			TCustomerAddrbook en = new TCustomerAddrbook();
			en.setAddrType(ConstantsUtil.CUSTOMER_ADDRTYPE_ELANKMAN);
			en.setCompanyId(companyId);
			en.setCustomerId(custId);
			en.setPhoneNo(o.getString("phoneNo"));
			en.setPhoneName(o.getString("name"));
			en.setRelation(o.getString("relation"));
			mans.add(en);
		}
		
		customerAddrbookService.saveBatch(mans,""+custId);
		// 刷新缓存
		Map<String,Object> m = new HashMap<String,Object>();
	    m.put("hasElinkman", 1);
	    CacheUtil.refreshCustRedis(reqJson.getString("token"), m);
	    
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 提交借款申请
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo submitLoan(HttpServletRequest request, JSONObject reqJson) throws Exception {
		return loanService.addLoan(reqJson);
	}
	
	/**
	 * 获取客户借款订单列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ResultInfo getLoans(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");
		int pageNo = reqJson.getInteger("pageNo") == null ? 1 : reqJson.getInteger("pageNo");
		int pageSize = reqJson.getInteger("pageSize") == null ? 25 : reqJson.getInteger("pageSize");

		int startRow = (pageNo - 1) * (pageSize);
		int endRow = pageSize;
		// 取得客户的所有借款订单：按申请时间降序
		StringBuffer sb = new StringBuffer("");
		sb.append("select a.id loanId,a.order_no orderNo,a.req_money reqMoney,a.req_date reqTime,a.end_time endTime, a.loan_status loanStatus,(case when a.loan_status in (3,6) and now()>a.end_time then 1 else 0 end) lateFlag")
		  .append(" from t_loan a where a.customer_id=? order by a.id desc")
		  .append(" limit " + startRow + "," + endRow);
		List<Map<String,Object>> ds = loanService.findMapBySql(sb.toString(), new Object[]{custId});
		
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(ds);
		return result;
	}
	
	/**
	 * 获取客户借款订单详情
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ResultInfo getLoanDetail(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long loanId = reqJson.getLong("loanId");

		// 取得客户的所有借款详情
		StringBuffer sb = new StringBuffer("");
		sb.append("select a.id loanId,a.order_no orderNo,a.req_money reqMoney,a.req_date reqTime,a.start_time startTime,a.end_time endTime, a.loan_status loanStatus,")
		  .append(" (case when a.loan_status in (3,6) and now()>a.end_time then 1 else 0 end) lateFlag,a.handle_fee handleFee,a.late_fee lateFee")
		  .append(" from t_loan a where a.id=?");
		Map<String,Object> map = loanService.findOneMapBySql(sb.toString(), new Object[]{loanId});
		// 如果存在滞纳金则获取滞纳金明细
		if (map != null){
			int lateFee = CommonUtil.getIntValue(map.get("lateFee"));
			if (lateFee > 0){
				String sql = "select a.type,a.create_time createTime,a.money from t_loan_latefee a where a.loan_id=? order by a.id asc";
				List<Map<String,Object>> fees = loanService.findMapBySql(sql, new Object[]{loanId});
				if (fees == null)
					fees = new ArrayList<Map<String,Object>>();
				map.put("latefees", fees);
			}else{
				map.put("latefees", new ArrayList<Map<String,Object>>());
			}
		}else{
			map = new HashMap<String,Object>();
		}
		
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(map);
		return result;
	}
	
	/**
	 * 获取客户还款订单列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ResultInfo getNeedPayLoans(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long custId = reqJson.getLong("custId");
		
		// 取得客户的还款汇总信息
		StringBuffer sb = new StringBuffer("");
		sb.append("select ifnull(sum(a.req_money+ifnull(a.late_fee-a.off_latefee,0)),0) sumMoney,")
		  .append(" min(a.end_time) recentPayDay, count(1) payBackNum, ifnull(sum(case when now()>a.end_time then 1 else 0 end),0) overDueNumber")
		  .append(" from t_loan a where a.customer_id=? and a.loan_status in (3,6)");
		Map<String,Object> ret = loanService.findOneMapBySql(sb.toString(), new Object[]{custId});
		// 如果paybackNum>0则再获取列表
		int payBackNum = CommonUtil.getIntValue(ret.get("payBackNum"));
		if (payBackNum > 0){
			sb = new StringBuffer("");
			sb.append("select a.id loanId,a.order_no orderNo,a.req_money reqMoney,ifnull(a.late_fee - a.off_latefee,0) lateFee,")
			  .append(" (case when now()>a.end_time then datediff(now(),a.end_time) else 0 end) lateDays,")
			  .append(" (case when now()<a.end_time then datediff(a.end_time,now()) else 0 end) remainDays,")
			  .append(" (case when now()>a.end_time then 1 else 0 end) lateFlag")
			  .append(" from t_loan a where a.customer_id=? and a.loan_status in (3,6) order by a.id asc");
			List<Map<String,Object>> ds = loanService.findMapBySql(sb.toString(), new Object[]{custId});
			ret.put("loans", ds);
		}else{
			List<Map<String,Object>> ds = new ArrayList<Map<String,Object>>();
			ret.put("loans", ds);
		}
		
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(ret);
		return result;
	}
}
